package com.github.axet.djvulibre;

import android.graphics.Bitmap;
import android.graphics.Rect;

import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class DjvuLibre {

    static {
        if (Config.natives) {
            System.loadLibrary("djvulibrejni");
        }
    }

    public static final String META_AUTHOR = "Author";
    public static final String META_TITLE = "Title";

    public static final int ZONE_PAGE = 1;
    public static final int ZONE_COLUMN = 2;
    public static final int ZONE_REGION = 3;
    public static final int ZONE_PARAGRAPH = 4;
    public static final int ZONE_LINE = 5;
    public static final int ZONE_WORD = 6;
    public static final int ZONE_CHARACTER = 7;

    protected long handle;

    protected FileDescriptor fd;
    protected FileInputStream is;
    protected FileChannel fc;

    public static class Page {
        public int width;
        public int height;
        public int dpi;

        public Page(int w, int h, int dpi) {
            this.width = w;
            this.height = h;
            this.dpi = dpi;
        }
    }

    public static class Bookmark {
        public int level;
        public String title;
        public int page;

        public Bookmark(int l, String t, int p) {
            level = l;
            title = t;
            page = p;
        }
    }

    public static class Text {
        public String[] text;
        public Rect[] bounds;

        public Text(String[] t, Rect[] b) {
            text = t;
            bounds = b;
        }
    }

    public DjvuLibre(FileDescriptor fd) {
        this.fd = fd;
        this.is = new FileInputStream(fd);
        this.fc = this.is.getChannel();
        create();
    }

    public native void create();

    public native void setCacheSize(int size);

    public native String getMeta(String key);

    public native Text getText(int page, int zone_type);

    public native int getPagesCount();

    public native Page getPageInfo(int index);

    public native void renderPage(Bitmap bm, int index, int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh);

    public native void close();

    public native Bookmark[] getBookmarks();

    protected byte[] read(int len) {
        ByteBuffer bb = ByteBuffer.allocate(len);
        try {
            int r = fc.read(bb);
            if (r == -1)
                return null;
            bb.flip();
            byte[] buf = new byte[r];
            bb.get(buf, 0, buf.length);
            return buf;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    protected long tell() {
        try {
            return fc.position();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
